package com.share.model;

import java.io.*;
import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

public class DBGifReader extends HttpServlet {

	Connection con;

	private static DataSource ds = null;
	static {
		try {
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		res.setContentType("image/gif");
		ServletOutputStream out = res.getOutputStream();

		try {
			con = ds.getConnection();
			Statement stmt = con.createStatement();
			String ord_no = req.getParameter("ord_no");
			ResultSet rs = stmt.executeQuery("select upd_picture from mems where ord_no = " + ord_no);

			if (rs.next()) {
				BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream("upd_picture"));
				byte[] buf = new byte[4 * 1024]; // 4K buffer
				// System.out.println(in.available());
				int len;
				while ((len = in.read(buf)) != -1) {
					out.write(buf, 0, len);
				}
				in.close();
			} else {
				InputStream in = new FileInputStream(getServletContext().getRealPath("NoData/nopic.jpg"));
				byte[] buf = new byte[4 * 1024]; // 4K buffer
				int len;
				while ((len = in.read(buf)) != -1) {
					out.write(buf, 0, len);
				}
				in.close();
				// res.sendError(HttpServletResponse.SC_NOT_FOUND);
			}
			rs.close();
			stmt.close();
		} catch (Exception e) {
			InputStream in = new FileInputStream(getServletContext().getRealPath("NoData/nopic.jpg"));
			byte[] buf = new byte[4 * 1024]; // 4K buffer
			int len;
			while ((len = in.read(buf)) != -1) {
				out.write(buf, 0, len);
			}

			// System.out.println(e);
		} finally {
			out.flush();
			out.close();
		}

	}

	// public void init() throws ServletException {
	// try {
	// Class.forName("oracle.jdbc.driver.OracleDriver");
	// con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
	// "hr", "123456");
	// }
	// catch (ClassNotFoundException e) {
	// throw new UnavailableException("Couldn't load JdbcOdbcDriver");
	// }
	// catch (SQLException e) {
	// throw new UnavailableException("Couldn't get db connection");
	// }
	// }

	public void destroy() {
		try {
			if (con != null)
				con.close();
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

}
